from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from apps.cart.models import Cart, CartItem
from apps.cart.serializers import CartSerializer, CartItemSerializer, CartDetailSerializer
from apps.goods.models import Goods
from apps.goods.serializers import GoodsSerializer
from utils import ResponseMessage
from utils.ResponseMessage import CartResponse


class CartAPIView(APIView):
    # @todo 在添加数据之前要先进行权限验证

    # http://localhost:8000/cart/list/
    # {
    #     "user_id": 3,
    #     "good_id": 4,
    #     "num": 1,
    #     "action":"add/remove"
    # }
    def post(self, request, *args, **kwargs):
        # if not request.user.get("status"):
        #     return JsonResponse("request.user", safe=False)
        # print(request.data)
        user_id = request.data.get('user_id')
        good_id = request.data.get('good_id')
        num = request.data.get('num')
        action = request.data.get('action')
        # print(cart_id, good_id, num)

        # 先把修改的总金额算出来，方便后面直接使用
        good = get_object_or_404(Goods, good_id=good_id)
        change_price = good.price * num

        cart = Cart.objects.filter(user_id=user_id).first()
        # print(cart)
        if cart:
            # 购物车存在，判断购物车里是否有该商品
            item = cart.item.filter(good=good_id).first()
            # print(item)
            if item:
                # 该商品在该购物车存在
                if action == 'add':
                    # 添加商品
                    item.num += num
                    # print(item.num)
                    if item.num != 0:
                        item.is_delete = False
                    item.save()
                    cart.total_goods_number += num
                    print()
                    cart.total_price += change_price
                    cart.save()
                    # print(item.num)
                    print("成功")
                    # return HttpResponse("商品又被您添加到购物车啦，喜欢就赶紧下单吧！")
                    return CartResponse.success("商品又被您添加到购物车啦，喜欢就赶紧下单吧！")
                elif action == 'remove':
                    # 移除商品
                    item.num -= num
                    if item.num == 0:
                        item.is_delete = True
                    item.save()
                    cart.total_goods_number -= num
                    cart.total_price -= change_price
                    cart.save()
                    # return HttpResponse("商品已经从购物车移除")
                    return CartResponse.success("商品已经从购物车移除")
            else:
                # 该商品在该购物车不存在
                item = cart.item.create(cart=cart, good=good, num=num)
                # item = CartItem.objects.create(cart=cart, good=good, num=num)
                # 修改Cart的实例属性数据
                cart.total_goods_number += num
                cart.total_price += change_price
                cart.save()
                # return HttpResponse("商品已经添加到您的购物车啦")
                return CartResponse.success("商品又被您添加到购物车啦，喜欢就赶紧下单吧！")
        else:
            # 购物车不存在
            # good = get_object_or_404(Goods, good_id=good_id)
            # # print(good.price)
            # total_price = good.price * num
            cart = Cart.objects.create(user_id=user_id, total_goods_number=num, total_price=change_price)
            cart_item = CartItem.objects.create(num=num, good_id=good_id, cart_id=cart.cart_id)
            return HttpResponse("购物车创建成功,商品添加成功")

    # http://localhost:8000/cart/list/?cart_id=1
    def get(self, request):
        # if not request.user.get("status"):
        #     return JsonResponse("request.user", safe=False)
        cart_id = request.GET.get('cart_id')
        # 使用 get_object_or_404 获取单个 Cart 实例
        # cart = Cart.objects.filter(cart_id=cart_id).first()
        cart = get_object_or_404(Cart, cart_id=cart_id)
        # 序列化 Cart 实例
        cart_data = CartSerializer(instance=cart).data
        # print(cart_data)

        # 使用 related_name 'item' 从 Cart 实例获取关联的 CartItem 实例
        cart_items = cart.item.filter(is_delete=False)
        # 序列化关联的 CartItem 实例
        cart_item_data = CartItemSerializer(instance=cart_items, many=True).data
        # print(cart_items)

        good_info_data = []
        for item in cart_items:
            # 直接通过外键来获取good对象
            good = item.good
            # print(good)
            # 序列化关联的 Goods 实例
            good_info = GoodsSerializer(good).data
            good_info_data.append(good_info)

        response_data = {
            'cart': cart_data,
            'cart_items': cart_item_data,
            'good': good_info_data
        }
        print(response_data)
        return ResponseMessage.CartResponse.success(response_data)

class CartDetailView(APIView):
    def post(self, request):
        # if not request.user.get("status"):
        #     return JsonResponse("request.user", safe=False)
        user_id = request.data.get('user_id')
        cart = Cart.objects.filter(user_id=user_id).first()
        cart_data = CartSerializer(instance=cart).data
        print(cart_data)

        # 使用 related_name 'item' 从 Cart 实例获取关联的 CartItem 实例
        cart_items = cart.item.filter(is_delete=False)
        # print(cart_items)
        cart_item_data = CartDetailSerializer(instance=cart_items, many=True).data
        print(cart_item_data)

        response_data = {
            'cart': cart_data,
            'cart_items': cart_item_data,
        }
        # print(response_data)
        return ResponseMessage.CartResponse.success(response_data)